package com.zyc.auto;

import com.zyc.pojo.Table;
import com.zyc.pojo.TableProperty;
import com.zyc.util.HappyUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 根据数据库自动生成所有表的 table
 * 作者：Rem
 * 时间：2021/1/27 19:57
 */
public class AutoTable {
    /**
     * 目标文件夹
     */
    private final String pathStr;
    /**
     * layui.css的路径
     */
    private final String layuiCss;
    /**
     * public.css的路径
     */
    private final String publicCss;
    /**
     * layui.js的路径
     */
    private final String layuiJs;
    /**
     * constantUtil的路径
     */
    private final String constantUtilPath;

    /**
     * 构造函数，用来初始化一些属性
     */
    public AutoTable() {
        pathStr = HappyUtil.properties.getProperty("targetPath");
        layuiCss = HappyUtil.properties.getProperty("layuiCss");
        publicCss = HappyUtil.properties.getProperty("publicCss");
        layuiJs = HappyUtil.properties.getProperty("layuiJs");
        constantUtilPath = HappyUtil.properties.getProperty("constantUtil");
    }

    /**
     * 入口函数，直接调用
     */
    public void start() throws IOException {
        //获取目标数据库中的所有表
        List<Table> tableList = HappyUtil.getTableList();
        //遍历所有表
        for (Table table : tableList) {
            //生成table.html文件
            produceTable(table);
        }
    }

    /**
     * 生成table.html文件
     *
     * @param table 生成文件的表
     */
    public void produceTable(Table table) throws IOException {
        StringBuilder tableText = new StringBuilder();
        String javaKey = table.getPrimaryKey().getPropertyLowerCamelName();
        String pojoName = table.getTableLowerCamelName();
        tableText.append("<!DOCTYPE html><html><head><meta charset=\"utf-8\">" +
                "<title>").append(pojoName).append("Table</title>" +
                "<meta name=\"renderer\" content=\"webkit\">" +
                "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">" +
                "<link rel=\"stylesheet\" href=\"").append(layuiCss).append("\" media=\"all\">" +
                "<link rel=\"stylesheet\" href=\"").append(publicCss).append("\" media=\"all\">" +
                "</head><body><div class=\"layuimini-container\"><div class=\"layuimini-main\">" +
                "<div class=\"demoTable\">\n" +
                "关键字查询：\n" +
                "<div class=\"layui-inline\">\n" +
                "<input class=\"layui-input\" name=\"title\" id=\"title\" autocomplete=\"off\">\n" +
                "</div>\n" +
                "<button class=\"layui-btn\" data-type=\"reload\">搜索</button>\n" +
                "</div>" +
                "<script type=\"text/html\" id=\"toolbarDemo\">" +
                "<div class=\"layui-btn-container\">" +
                "<button class=\"layui-btn layui-btn-normal layui-btn-sm data-add-btn\" lay-event=\"add\"> 添加</button>" +
                "<button class=\"layui-btn layui-btn-sm layui-btn-danger data-delete-btn\" lay-event=\"delete\"> 删除</button>" +
                "</div>" +
                "</script>" +
                "<table class=\"layui-hide\" id=\"currentTableId\" lay-filter=\"currentTableFilter\"></table>" +
                "<script type=\"text/html\" id=\"currentTableBar\">" +
                "<a class=\"layui-btn layui-btn-normal layui-btn-xs data-count-edit\" lay-event=\"edit\">编辑</a>" +
                "<a class=\"layui-btn layui-btn-xs layui-btn-danger data-count-delete\" lay-event=\"delete\">删除</a>" +
                "</script>" +
                "<script type=\"text/html\" id=\"currentTableBar1\">" +
                "</script></div></div>" +
                "<style type=\"text/css\">.layui-table-cell {height: auto;}" +
                "</style>" +
                "<script src=\"").append(layuiJs).append("\" charset=\"utf-8\"></script>" +
                "<script src=\"").append(constantUtilPath).append("\"></script>" +
                "<script>layui.use(['form', 'table','util'], function () {" +
                "var $ = layui.jquery,form = layui.form,table = layui.table,util = layui.util;" +
                "table.render({elem: '#currentTableId', url: host + \"/").append(pojoName).append(".do/selectByCondition\"" +
                ",headers: {\n" +
                "token: sessionStorage.getItem(\"token\")\n" +
                "},\n" +
                "parseData: function(res) { //res 即为原始返回的数据\n" +
                "if(res.code == -1004) {\n" +
                "layer.msg(\"身份验证失败，请重新登录\", function() {\n" +
                "location.href = \"../../../index.html\";\n" +
                "});\n" +
                "}\n" +
                "if(res.code != 0) {\n" +
                "layer.msg(res.msg);\n" +
                "}\n" +
                "return {\n" +
                "\"code\": res.code, //解析接口状态\n" +
                "\"msg\": res.msg, //解析提示文本\n" +
                "\"count\": res.data.total, //解析数据长度\n" +
                "\"data\": res.data.list //解析数据列表\n" +
                "};\n" +
                "}" +
                ", toolbar: '#toolbarDemo'" +
                ", cellMinWidth: 150" +
                ", defaultToolbar: ['filter', 'exports', 'print', {" +
                "title: '提示'," +
                "layEvent: 'LAYTABLE_TIPS'," +
                "icon: 'layui-icon-tips'" +
                "}]" +
                ", cols: [[{type: 'checkbox', width: 50}");
        for (TableProperty tableProperty : table.getTableProperties()) {
            String propertyName = tableProperty.getPropertyLowerCamelName();
            if ("Date".equals(propertyName)) {
                tableText.append(", {field: '").append(propertyName)
                        .append("', width: 150, title: '").append(tableProperty.getComment()).append("'}");
            } else {
                tableText.append(", {field: '").append(propertyName)
                        .append("', title: '").append(tableProperty.getComment()).append("'}");
            }
        }
        tableText.append(", {title: '操作', toolbar: '#currentTableBar', align: \"center\", width: 150}]]," +
                " limits: [2, 4, 8, 10, 15, 20],limit: 15,page: true,skin: 'line'});" +
                "var active = {\n" +
                "reload: function() {\n" +
                "//执行重载\n" +
                "table.reload('currentTableId', {\n" +
                "page: {\n" +
                "curr: 1 //重新从第 1 页开始\n" +
                "},\n" +
                "where: {\n" +
                "title: $('#title').val()\n" +
                "}\n" +
                "});\n" +
                "}\n" +
                "};\n" +
                "\n" +
                "$('.demoTable .layui-btn').on('click', function() {\n" +
                "var type = $(this).data('type');\n" +
                "active[type] ? active[type].call(this) : '';\n" +
                "});" +
                "table.on('toolbar(currentTableFilter)', " +
                "function (obj) {if (obj.event === 'add') {" +
                "var index = layer.open({title: '添加用户',type: 2,shade: 0.2,maxmin: true,shadeClose: true," +
                "area: ['90%', '90%']," +
                "content: '../add/").append(pojoName).append("Add.html'," +
                "end: function () {table.reload('currentTableId');}});" +
                "$(window).on(\"resize\", function () {layer.full(index);});" +
                "} else if (obj.event === 'delete') {" +
                "var checkStatus = table.checkStatus('currentTableId')" +
                ", data = checkStatus.data;" +
                "layer.alert(JSON.stringify(data));}});" +
                "table.on('checkbox(currentTableFilter)', function (obj) {" +
                "});" +
                "table.on('tool(currentTableFilter)', function (obj) {" +
                "var data = obj.data;" +
                "if (obj.event === 'edit') {" +
                "localStorage.setItem(\"").append(javaKey).append("\", data.").append(javaKey).append(");var index = layer.open({" +
                "title: '编辑用户'," +
                "type: 2," +
                "shade: 0.2," +
                "maxmin: true," +
                "shadeClose: true," +
                "area: ['90%', '90%']," +
                "content: '../edit/").append(pojoName).append("Edit.html'," +
                "end: function () {" +
                "table.reload('currentTableId');}});" +
                "$(window).on(\"resize\", function () {" +
                "layer.full(index);});" +
                "return false;" +
                "} else if (obj.event === 'delete') {" +
                "layer.confirm('真的要删除么', function (index) {" +
                "$.post({url: \"/").append(pojoName).append(".do/delete\"," +
                "data: {id: obj.data.").append(javaKey).append("}," +
                "success: function (res) {" +
                "layer.alert(res.msg);" +
                "if (res.code == 0) {" +
                "obj.del();}}});" +
                "layer.close(index);});}});});" +
                "</script></body></html>");
        File path = new File(pathStr + "/pages/table");
        if (!path.exists() && !path.mkdirs()) {
            System.err.println("文件夹生成错误！" + path);
            return;
        }
        File file = new File(pathStr + "/pages/table/" + pojoName + "Table.html");
        System.out.println(file.getAbsolutePath());
        FileWriter fw = new FileWriter(file);
        fw.write(tableText.toString());
        HappyUtil.closeAll(fw);
    }
}
